package middleware

import (
	uuid "github.com/satori/go.uuid"
	"smart-sensor-cloud/pkg/context"
	"smart-sensor-cloud/pkg/log"
	"strings"

	"github.com/gin-gonic/gin"
)

const (
	RequestIDHeaderKey = "X-Request-ID"
)

func RequestID(skippers ...Skipper) gin.HandlerFunc {
	return func(c *gin.Context) {
		if SkipHandler(c, skippers...) {
			c.Next()
			return
		}

		requestID := ""

		if requestID = GetRequestIDFromRequest(c); requestID == "" {
			requestID = strings.Replace(uuid.Must(
				uuid.NewV4(),
				nil,
			).String(), "-", "", -1)
		}

		ctx := context.WithRequestID(c.Request.Context(), requestID)
		ctx = log.NewRequestIDContext(ctx, requestID)
		c.Request = c.Request.WithContext(ctx)
		c.Writer.Header().Set(RequestIDHeaderKey, requestID)
		c.Next()
	}
}
